package cn.gene.timeyan.ams.webapi.service.impl;

import cn.gene.timeyan.ams.service.IMapService;
import cn.gene.timeyan.ams.webapi.utils.MapUtils;
import cn.gene.timeyan.common.exception.TimeyanServiceException;
import cn.gene.timeyan.common.restful.ResponseCode;
import com.alibaba.fastjson.JSONObject;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@DubboService
public class MapServiceImpl implements IMapService {
    private String ak="T4MLkvyr7Ztgr4wmsHsenZW46v2MmudG";


    /**
     * 依据ip获取地理位置
     * @param request
     * @return
     */
    @Override
    public Map<String, Object> getAddressByUserIP(HttpServletRequest request) {
        System.out.println();
        String ip= MapUtils.getIp(request);
//        String ip="39.129.249.120";
//        System.out.println("定位");
        String url="https://api.map.baidu.com/location/ip?ak="+ak+"&ip="+ip+"&coor=bd09ll";
        JSONObject info=new JSONObject();
        try {
            //获取信息
            info = MapUtils.readJsonFromUrl(url);
        } catch (IOException e) {
            System.out.println(e.getMessage());
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"定位失败");
        }
        if ((Integer) info.get("status")!=0){
            System.out.println(info);
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"定位失败");
        }
        //详细地址
        JSONObject add = (JSONObject) ((JSONObject) info.get("content")).get("address_detail");
        //中心点
        JSONObject point = (JSONObject) ((JSONObject) info.get("content")).get("point");
        //获取省
        String province=add.getString("province");
        //获取城市
        String city=add.getString("city");
        //获取中心点经度
        String x=point.getString("x");
        //获取中心点纬度
        String y=point.getString("y");

        Map<String,Object> result=new HashMap<>();
        result.put("province",province);
        result.put("city",city);
        result.put("x",x);
        result.put("y",y);
        return result;
    }
}
